/*
   Hook into the keyboard events
   Created by Randall Maas, Sunday January 25 2009
   Copyright (c) 2009, Randall Maas
   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:

   Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.

   Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

   Neither the name of Blackwood Designs, LLC nor the names of its contributors
   may be used to endorse or promote products derived from this software without
   specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
   AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
   THE POSSIBILITY OF SUCH DAMAGE.
*/

using System;
using System . Collections. Generic;
using System . Runtime . InteropServices;
using System . Windows . Forms;

public static partial class Win32
{
   #region Hot Key
   /// <summary>
   /// The window we use to receive and handle the hot key events
   /// </summary>
   static HotKeyWindow _HotKeyWindow;

   /// <summary>
   /// Registers a hot key in the system.
   /// </summary>
   /// <param name="key">The key itself that is associated with the hot key.</param>
   /// <param name="handler">The handler for this key</param>
   internal static bool RegisterHotKey(Keys key, KeyEventHandler Handler)
   {
      // Create the HotKeyWindow, if needed
      if (null == _HotKeyWindow)
        _HotKeyWindow = new HotKeyWindow();

      // register the hot key.
      return _HotKeyWindow . RegisterHotKey(key, Handler);
   }

   /// <summary>
   /// Used to dispose the hot key window
   /// </summary>
   internal static void ReleaseHotKeys()
   {
      HotKeyWindow X = _HotKeyWindow;
      _HotKeyWindow = null;
      if (null != X)
        X . Dispose();
   }
   #endregion
}


/// <summary>
/// Represents the window that is used internally to get the messages.
/// </summary>
class HotKeyWindow : NativeWindow, IDisposable
{
   #region Constructor / Destructor
   /// <summary>
   /// Creates the window to receive the hot key events
   /// </summary>
   public HotKeyWindow()
   {
      // create the handle for the window.
      CreateHandle(new CreateParams());
   }

   ~HotKeyWindow()
   {
      Dispose();
   }

   public void Dispose()
   {
      // unregister all the registered hot keys.
      while (keyIdx > 0)
       UnregisterHotKey(Handle, keyIdx--);

      DestroyHandle();
      GC . SuppressFinalize(this);
   }
   #endregion

   #region Manage Hot Keys
   /// <summary>
   /// The window manager maing
   /// </summary>
   private static int keyIdx = 0;

   /// <summary>
   /// Maps the key to the handler
   /// </summary>
   internal Dictionary<Keys, KeyEventHandler> KeyHandler = new Dictionary<Keys, KeyEventHandler>();

   /// <summary> The RegisterHotKey function defines a system-wide hot key </summary>
   /// <param name="wnd">Handle to the window that will receive WM_HOTKEY messages
   /// generated by the hot key.</param>
   /// <param name="id">Specifies the identifier of the hot key.</param>
   /// <param name="fsModifiers">Specifies keys that must be pressed in combination with the key
   /// specified by the 'vk' parameter in order to generate the WM_HOTKEY message.</param>
   /// <param name="vk">Specifies the virtual-key code of the hot key</param>
   /// <returns><c>true</c> if the function succeeds, otherwise <c>false</c></returns>
   /// <seealso cref="http://msdn.microsoft.com/en-us/library/ms646309(VS.85).aspx"/>
   [DllImport("user32.dll")]
   [return: MarshalAs(UnmanagedType.Bool)]
   private static extern bool RegisterHotKey(IntPtr Wnd, int id, uint fsModifiers, uint vk);

   [Flags]
   enum KeyModifier
   {
      ALT    = 1,
      CONTROL= 2,
      SHIFT  = 4,
      WIN    = 8
   }


   /// <summary>
   /// Unregisters the hot key with Windows.
   /// </summary>
   /// <param name="Wnd">Handle to the window receiving the hot key events</param>
   /// <param name="id"></param>
   /// <returns></returns>
   [DllImport("user32.dll")]
   [return: MarshalAs(UnmanagedType.Bool)]
   private static extern bool UnregisterHotKey(IntPtr Wnd, int id);

   /// <summary>
   /// Registers a hot key in the system.
   /// </summary>
   /// <param name="key">The key itself that is associated with the hot key.</param>
   /// <param name="handler">The handler for this key</param>
   internal bool RegisterHotKey(Keys key, KeyEventHandler Handler)
   {
      KeyHandler[key] = Handler;

      // Figure out the modifiers from the key
      uint modifiers = 0;

      if (0 != (key & Keys.Alt))
        modifiers |= (uint) KeyModifier . ALT;

      if ((key & Keys.Control) == Keys.Control)
        modifiers |= (uint) KeyModifier . CONTROL;

      if ((key & Keys.Shift) == Keys.Shift)
        modifiers |= (uint) KeyModifier . SHIFT;
//      if (0 != (key & Keys . Win))
//        modifiers |= MOD_WIN;

      Keys k = key & ~Keys.Control & ~Keys.Shift & ~Keys.Alt;

      // register the hot key.
      // Note: pinvoke.net suggests using a globalatom instead of our own number...
      return RegisterHotKey(Handle, ++keyIdx, (uint)modifiers, (uint)k);
   }

   #endregion

   /// <summary>
   /// A helper that represents a constant value commonly used
   /// </summary>
   static IntPtr I1 = new IntPtr(1);

   /// <summary>
   /// Overridden to get the notifications.
   /// </summary>
   /// <param name="m"></param>
   protected override void WndProc(ref Message m)
   {
      base.WndProc(ref m);
#if false
      if ((int) WM.SYSCOMMAND == m.Msg && SC_MONITORPOWER == m.WParam.ToInt32())
        MonPower = (MonitorPower) m.LParam;
#endif

      // check if we got a hot key pressed.
      if (WM . HOTKEY != (WM) m.Msg)
        return ;

      m . Result = I1;
      // get the keys.
      Keys key = (Keys)(((int)m.LParam >> 16) & 0xFFFF);
      KeyModifier modifier = (KeyModifier) ((int)m.LParam & 0xFFFF);

      // Revise to get the proper key enumeration
      if (0 != (modifier & KeyModifier . ALT))
        key |= Keys.Alt;

      if (0 != (modifier & KeyModifier . CONTROL))
        key |= Keys.Control;

      if (0 != (modifier & KeyModifier . SHIFT))
        key |= Keys.Shift;

//      if (0 != (modifier & MOD_WIN))
//        key |= Keys.Win;

      KeyEventHandler Hdlr;
      if (KeyHandler . TryGetValue(key, out Hdlr))
        Hdlr(this, new KeyEventArgs(key));
   }
}
